﻿// Microsoft Public License (Ms-PL)
// nRoute v5 (http://nroute.codeplex.com)
// Modifié par So@t

using System;
using System.Windows;
using System.Windows.Interactivity;

namespace CPN.PJN.Silverlight.UI.Interactions.Behaviors
{
    /// <summary>
    /// Affiche ou non un composant graphique en fonction d'une valeur booléenne
    /// Si la valeur est vraie le composant est affichée, sinon il est caché
    /// </summary>
    public class BoolValueVisibilityBehavior : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(bool), typeof(BoolValueVisibilityBehavior),
            new PropertyMetadata(false, new PropertyChangedCallback(OnValueChanged)));

        #region Properties

        public bool Value
        {
            get { return Convert.ToBoolean(GetValue(ValueProperty)); }
            set { SetValue(ValueProperty, value); }
        }

        public bool Negate { get; set; }

        #endregion

        #region Trigger Related

        protected override void OnAttached()
        {
            base.OnAttached();
            UpdateVisibility(Value);
        }

        #endregion

        #region Handlers

        static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BoolValueVisibilityBehavior)d).UpdateVisibility(Convert.ToBoolean(e.NewValue));
        }

        void UpdateVisibility(bool value)
        {
            if (this.AssociatedObject == null) return;

            var _visible = value;
            if (Negate) _visible = !_visible;
            this.AssociatedObject.Visibility = _visible ? Visibility.Visible : Visibility.Collapsed;
        }

        #endregion

    }
}
